package com.hannah.benchmark;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class BeetlBenchmark {

	private GroupTemplate gt;
	private Map<String, Object> paras = new HashMap<>();

	@Setup
	public void init() {
		try {
			Configuration cfg = Configuration.defaultConfiguration();
			gt = new GroupTemplate(new StringTemplateResourceLoader(), cfg);
			
			paras.put("a", 23342423);
			paras.put("b", 435454);
			paras.put("c", 121243);
			paras.put("d", 23);
			
		} catch (IOException e) {
			throw new RuntimeException("初始化Beetl资源加载器失败", e);
		}
		System.out.println("准备工作就绪！");
	}

	@Benchmark
	public void testArith() {
		Map result = gt.runScript("return (a+b-c)*d;", paras);
//		System.out.println(result);
	}

	@Benchmark
	public void testObject() {
		Map result = gt.runScript("var object = {f1: a, f2: a+b, f3: c, f4: (a+b-c)*d}; ", paras);
//		System.out.println(result);
	}

	public static void main(String[] args) {
		BeetlBenchmark bm = new BeetlBenchmark();
		bm.init();
		bm.testObject();
	}
}
